<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   
class Auth extends Controller {
 
    function __construct() 
    {

        parent::__construct();
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->database();
    }
 
    //redirect if needed, otherwise display the user list
    function index() 
    {
    	if (!$this->ion_auth->logged_in()) {
	    	//redirect them to the login page
			redirect('auth/login'); //REN Change:  Remove 'refresh option to fix on PPG's network
    	}
    	elseif (!$this->ion_auth->is_admin()) {
    		//redirect them to the home page because they must be an administrator to view this
			redirect($this->config->item('base_url')); //REN Change:  Remove 'refresh option to fix on PPG's network
    	}
    	else 
    	{
	        //set the flash data error message if there is one
	        $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
	        
    		//list the users
    		$data['users'] = $this->ion_auth->get_users_array();
    		
			$data['title'] = '';
			$data['view'] = 'auth/index';
			$this->load->vars($data);
			$this->load->view('master_view', $data);  
    	}
    }
    
    //log the user in
    function login() 
    {
        //validate form input
    	$this->form_validation->set_rules('username', 'User Name', 'required');
	    $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() == true) { //check to see if the user is logging in
        	//check for "remember me"
        	if ($this->input->post('remember') == 1) {
        		$remember = true;
        	}
        	else {
        		$remember = false;
        	}
        	
        	if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember)) { //if the login is successful
	        	//redirect them back to the home page
	        	$this->session->set_flashdata('message', $this->ion_auth->messages());
	        	redirect($this->config->item('base_url')); //REN Change:  Remove 'refresh option to fix on PPG's network
	        }
	        else { //if the login was un-successful
	        	//redirect them back to the login page
	        	$this->session->set_flashdata('message', $this->ion_auth->errors());
	        	////REN Change:  Remove 'refresh option to fix on PPG's network
	        	redirect('auth/login'); //use redirects instead of loading views for compatibility with MY_Controller libraries
	        }
        }
		else 
		{  
			//the user is not logging in so display the login page
	        //set the flash data error message if there is one
	        $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
		    
			$data['username']      = array('name'			=> 'username',
                                              'id'				=> '_username',
                                              'type'			=> 'text',
								              'class'			=>	'text-box',
								              'autocomplete'	=>	'off',
                                              'value'   => $this->form_validation->set_value('username'),
                                             );
            $data['password']   = array(	'name'		=> 'password',
                                              	'id'		=> '_password',
                                              	'type'		=> 'password',
            									'class'		=>	'text-box'
                                             );
	        $data['additional_javascript_doc_ready_functions'] = '$(".submit-button", ".auth-div").button();$(\'#_username\').focus();';
			$data['title'] = 'Login Page';
			$data['view'] = 'auth/login';
			$this->load->vars($data);
			$this->load->view('master_view', $data);  
		}
    }
    
    //log the user out
	function logout() 
	{
        $this->data['title'] = "Logout";
        
        //log the user out
        $logout = $this->ion_auth->logout();
			    
        //redirect them back to the page they came from
        redirect('auth'); //REN Change:  Remove 'refresh option to fix on PPG's network
    }
    
    //change password
	function change_password() 
	{	    
	    $this->form_validation->set_rules('old', 'Old password', 'required');
	    $this->form_validation->set_rules('new', 'New Password', 'required|min_length['.$this->config->item('min_password_length', 'ion_auth').']|max_length['.$this->config->item('max_password_length', 'ion_auth').']|matches[new_confirm]');
	    $this->form_validation->set_rules('new_confirm', 'Confirm New Password', 'required');
	   
	    if (!$this->ion_auth->logged_in()) {
	    	redirect('auth/login');//REN Change:  Remove 'refresh option to fix on PPG's network
	    }
	    $user = $this->ion_auth->get_user($this->session->userdata('user_id'));
	    
	    if ($this->form_validation->run() == false) { //display the form
	        //set the flash data error message if there is one
	        $data['message']							=	(validation_errors()) ? validation_errors() : $this->session->flashdata('message');
			
	        $data['old_password']					= array('name'    => 'old',
		                                               	  'id'      => '_old',
		                                              	  'type'    => 'password',
		                                                 );
	        $data['new_password']					= array('name'    => 'new',
		                                               	  'id'      => '_new',
		                                              	  'type'    => 'password',
		                                                 );
        	$data['new_password_confirm']   = array('name'    => 'new_confirm',
                                                      	  'id'      => '_new_confirm',
                                                      	  'type'    => 'password',
        												 );
        	$data['user_id']                = array('name'    => 'user_id',
                                                      	  'id'      => '_user_id',
                                                      	  'type'    => 'hidden',
        												  'value'   => $user->id,
        												 );
	        

								        												
					$data['title'] = 'Change Password';
					$data['view'] = 'auth/change_password';
					$this->load->vars($data);
					$this->load->view('master_view', $data);  
	    }
	    else {
	        $identity = $this->session->userdata($this->config->item('identity', 'ion_auth'));
	        
	        $change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));
		
    		if ($change) { //if the password was successfully changed
    			$this->session->set_flashdata('message', $this->ion_auth->messages());
    			$this->logout();
    		}
    		else 
    		{
    			$this->session->set_flashdata('message', $this->ion_auth->errors());
    			//redirect('auth/change_password', 'refresh');
    			
					$data['title'] = 'Password Changed';
					$data['view'] = 'auth/change_password';
					$this->load->vars($data);
					$this->load->view('master_view', $data);  
    		}
    		
	    }
	}
	
	//forgot password
	function forgot_password() 
	{
		$this->form_validation->set_rules('email', 'Email Address', 'required');
	    if ($this->form_validation->run() == false) {
	    	//setup the input
	    	$this->data['email'] = array('name'    => 'email',
                                         'id'      => 'email',
        						   	    );
	    	//set any errors and display the form
        	$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
    		$this->load->view('auth/forgot_password', $this->data);
	    }
	    else {
	        //run the forgotten password method to email an activation code to the user
			$forgotten = $this->ion_auth->forgotten_password($this->input->post('email'));
			
			if ($forgotten) { //if there were no errors
				$this->session->set_flashdata('message', $this->ion_auth->messages());
				//REN Change:  Remove 'refresh option to fix on PPG's network
	            redirect("auth/login"); //we should display a confirmation page here instead of the login page
			}
			else {
				$this->session->set_flashdata('message', $this->ion_auth->errors());
				//REN Change:  Remove 'refresh option to fix on PPG's network
	            redirect("auth/forgot_password");
			}
	    }
	}
	
	//reset password - final step for forgotten password
	public function reset_password($code) 
	{
		$reset = $this->ion_auth->forgotten_password_complete($code);
		
		if ($reset) {  //if the reset worked then send them to the login page
			$this->session->set_flashdata('message', $this->ion_auth->messages());
            redirect("auth/login"); //REN Change:  Remove 'refresh option to fix on PPG's network
		}
		else { //if the reset didnt work then send them back to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
            redirect("auth/forgot_password"); //REN Change:  Remove 'refresh option to fix on PPG's network
		}
	}

	//activate the user
	function activate($id, $code=false) 
	{        
		$activation = $this->ion_auth->activate($id, $code);
		
        if ($activation) {
			//redirect them to the auth page
	        $this->session->set_flashdata('message', $this->ion_auth->messages());
	        redirect("auth"); //REN Change:  Remove 'refresh option to fix on PPG's network
        }
        else {
			//redirect them to the forgot password page
	        $this->session->set_flashdata('message', $this->ion_auth->errors());
	        redirect("auth/forgot_password"); //REN Change:  Remove 'refresh option to fix on PPG's network
        }
    }
    
    //deactivate the user
	function deactivate($id = NULL) 
	{
		// no funny business, force to integer
		$id = (int) $id;
		
		$this->load->library('form_validation');
		$this->form_validation->set_rules('confirm', 'confirmation', 'required');
		$this->form_validation->set_rules('id', 'user ID', 'required|is_natural');
				
		if ( $this->form_validation->run() == FALSE )
		{
			// insert csrf check
			$this->data['csrf']	=	$this->_get_csrf_nonce();
			$this->data['user']	=	$this->ion_auth->get_user($id);
    		$this->load->view('auth/deactivate_user', $this->data);
		}
		else
		{
			// do we really want to deactivate?
			if ( $this->input->post('confirm') == 'yes' )
			{
				// do we have a valid request?
				if ( $this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id') )
				{
					show_404();
				}

				// do we have the right userlevel?
				if ( $this->ion_auth->logged_in() && $this->ion_auth->is_admin() )
				{
					$this->ion_auth->deactivate($id);
				}
			}
	
			//redirect them back to the auth page
			redirect('auth'); //REN Change:  Remove 'refresh option to fix on PPG's network
		}
    }
    
    //create a new user
	function create_user() 
	{
		$this->data['title'] = "Create User";
		$this->load->model('Facility_model');
		$this->load->model('Group_model');
              
		if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
			redirect('auth');  //REN Change:  Remove 'refresh option to fix on PPG's network
		}
		
        //validate form input
        $this->form_validation->set_rules('user_name', 'User Name', 'required|xss_clean');
    	$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
    	$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
    	$this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
    	$this->form_validation->set_rules('group', 'Group', 'required');
    	$this->form_validation->set_rules('password', 'Password', 'required|min_length['.$this->config->item('min_password_length', 'ion_auth').']|max_length['.$this->config->item('max_password_length', 'ion_auth').']|matches[password_confirm]');
    	$this->form_validation->set_rules('password_confirm', 'Password Confirmation', 'required');
    	$this->form_validation->set_rules('current_facility_id', 'Facility', 'required');

		if ($this->form_validation->run() == true) 
        {
        	
			$username  = strtolower($this->input->post('user_name'));
			$email     = $this->input->post('email');
			$password  = $this->input->post('password');
        	
			$additional_data	=	array('first_name'	=>	$this->input->post('first_name'),
											'last_name'	=>	$this->input->post('last_name'),
											//'company'	=>	$this->input->post('company'),
											//'phone'		=>	$this->input->post('phone1') .'-'. $this->input->post('phone2') .'-'. $this->input->post('phone3'),
								'current_facility_id'	=>	$this->input->post('current_facility_id'),
											'group_id'		=>	$this->input->post('group'),
        				       );
        }
        if ($this->form_validation->run() == true && $this->ion_auth->register($username,$password,$email,$additional_data)) 
        { 
        	//check to see if we are creating the user
			//redirect them back to the admin page
        	$this->session->set_flashdata('message', "User Created");
       		redirect("auth");  //REN Change:  Remove 'refresh option to fix on PPG's network
		} 
		else 
		{ 
			//display the create user form
	        //set the flash data error message if there is one
	        
			$data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
			
			$data['user_name']	= array('name'   => 'user_name',
		                                              'id'      => '_userName',
		                                              'type'    => 'text',
													 'autocomplete' => 'off',
		                                              'value'   => $this->form_validation->set_value('user_name'),
					);

			$data['first_name']	= array('name'   => 'first_name',
		                                              'id'      => '_firstName',
		                                              'type'    => 'text',
													 	'autocomplete' => 'off',
		                                              'value'   => $this->form_validation->set_value('first_name'),
		                                             );
            $data['last_name']	= array('name'   => 'last_name',
		                                              'id'      => '_lastName',
		                                              'type'    => 'text',
													 	'autocomplete' => 'off',
		                                              'value'   => $this->form_validation->set_value('last_name'),
		                                             );
            $data['email']		= array('name'    => 'email',
		                                              'id'      => '_email',
		                                              'type'    => 'text',
													 	'autocomplete' => 'off',
		                                              'value'   => $this->form_validation->set_value('email'),
		                                             );
		                                             
		    $data['password']           = array('name'    => 'password',
		                                              'id'      => '_password',
		                                              'type'    => 'password',
		                                              'value'   => $this->form_validation->set_value('password'),
		                                             );
            $data['password_confirm']   = array('name'    => 'password_confirm',
                                                      'id'      => '_passwordConfirm',
                                                      'type'    => 'password',
                                                      'value'   => $this->form_validation->set_value('password_confirm'),
                                                     );
            
			$data['current_facility_id']		= $this->form_validation->set_value('current_facility_id');
			
			$data['group_id']		= $this->form_validation->set_value('group_id');
            
			//$this->load->view('auth/create_user', $this->data);
			$data['additional_javascript_doc_ready_functions'] = '$(".submit-button", ".auth-div").button();$(\'#_firstname\').focus();';
			$facility_lookup = $this->Facility_model->get_facility_list();
			$data['facility_list'] = set_lookup($facility_lookup,'facility_id','facility_name', BLANK_ROW);
			$group_lookup = $this->Group_model->get_group_list();
			$data['group_list'] = set_lookup($group_lookup,'id','description', BLANK_ROW);
			$data['title'] = 'Login Page';
			$data['view'] = 'auth/create_user';
			$this->load->vars($data);
			$this->load->view('master_view', $data);  
			
		}
    }
    
    
	function _get_csrf_nonce()
	{
		$this->load->helper('string');
		$key	= random_string('alnum', 8);
		$value	= random_string('alnum', 20);
		$this->session->set_flashdata('csrfkey', $key);
		$this->session->set_flashdata('csrfvalue', $value);
		
		return array($key=>$value);
	}
	
	function _valid_csrf_nonce()
	{
			if ( $this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
				 $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
			{
				return TRUE;
			}
			else
			{
				return FALSE;
			}
	}
}
